use crate::utils::templates;
use anyhow::Result;
use colored::*;
use std::fs;
use std::path::Path;

pub async fn run(
    name: String,
    template: String,
    typescript: bool,
    output_dir: String,
) -> Result<()> {
    println!("{} {} Vue3 project", "🚀 Creating".cyan().bold(), name);

    let project_dir = Path::new(&output_dir).join(&name);

    // 创建项目目录结构
    create_project_structure(&project_dir, &template, typescript).await?;

    // 生成配置文件
    generate_config_files(&project_dir, &name, &template, typescript).await?;

    // 生成源码文件
    generate_source_files(&project_dir, &template, typescript).await?;

    // 生成样式文件
    generate_style_files(&project_dir).await?;

    println!(
        "{} {} Vue3 project created successfully!",
        "✅".green(),
        name
    );
    println!("{} Next steps:", "📋".blue());
    println!("  cd {}", name);
    println!("  npm install");
    println!("  npm run dev");

    Ok(())
}

async fn create_project_structure(
    project_dir: &Path,
    template: &str,
    typescript: bool,
) -> Result<()> {
    // 基础目录结构
    let dirs = [
        "src",
        "src/components",
        "src/views",
        "src/assets",
        "src/assets/css",
        "src/utils",
        "public",
    ];

    // 根据模板添加额外目录
    let mut extra_dirs = Vec::new();
    match template {
        "router" | "full" => {
            extra_dirs.push("src/router");
        }
        _ => {}
    }

    if template == "pinia" || template == "full" {
        extra_dirs.push("src/stores");
    }

    if typescript {
        extra_dirs.push("src/types");
    }

    // 创建所有目录
    for dir in dirs.iter().chain(extra_dirs.iter()) {
        fs::create_dir_all(project_dir.join(dir))?;
    }

    println!("{} Project structure created", "📁".blue());
    Ok(())
}

async fn generate_config_files(
    project_dir: &Path,
    name: &str,
    template: &str,
    typescript: bool,
) -> Result<()> {
    // package.json
    let package_json = templates::vue3_package_json(name, template, typescript);
    fs::write(project_dir.join("package.json"), package_json)?;

    // vite.config.js/ts
    let vite_config = if typescript {
        templates::vue3_vite_config_ts()
    } else {
        templates::vue3_vite_config_js()
    };
    let config_ext = if typescript { "ts" } else { "js" };
    fs::write(
        project_dir.join(format!("vite.config.{}", config_ext)),
        vite_config,
    )?;

    // index.html
    let index_html = templates::vue3_index_html(name, typescript);
    fs::write(project_dir.join("index.html"), index_html)?;

    // TypeScript 配置 - 简化版本，避免复杂的项目引用
    if typescript {
        let tsconfig = templates::vue3_tsconfig_json();
        fs::write(project_dir.join("tsconfig.json"), tsconfig)?;

        // env.d.ts 环境类型声明文件
        let env_dts = templates::vue3_env_dts();
        fs::write(project_dir.join("env.d.ts"), env_dts)?;
    }

    // 环境变量文件
    let env_content = templates::vue3_env_file();
    fs::write(project_dir.join(".env"), env_content)?;

    // .gitignore
    let gitignore = templates::vue3_gitignore();
    fs::write(project_dir.join(".gitignore"), gitignore)?;

    // README.md
    let readme = templates::vue3_readme(name, template, typescript);
    fs::write(project_dir.join("README.md"), readme)?;

    println!("{} Configuration files generated", "⚙️".yellow());
    Ok(())
}

async fn generate_source_files(project_dir: &Path, template: &str, typescript: bool) -> Result<()> {
    let ext = if typescript { "ts" } else { "js" };

    // main.ts/js
    let main_content = templates::vue3_main_file(template, typescript);
    fs::write(project_dir.join(format!("src/main.{}", ext)), main_content)?;

    // App.vue
    let app_vue = templates::vue3_app_vue(template);
    fs::write(project_dir.join("src/App.vue"), app_vue)?;

    // 基础组件
    let hello_world = templates::vue3_hello_world_component(typescript);
    fs::write(
        project_dir.join("src/components/HelloWorld.vue"),
        hello_world,
    )?;

    // 根据模板生成额外文件
    match template {
        "router" | "full" => {
            // 路由配置
            let router_content = templates::vue3_router_config(typescript);
            fs::write(
                project_dir.join(format!("src/router/index.{}", ext)),
                router_content,
            )?;

            // 视图组件
            let home_view = templates::vue3_home_view();
            fs::write(project_dir.join("src/views/HomeView.vue"), home_view)?;

            let about_view = templates::vue3_about_view();
            fs::write(project_dir.join("src/views/AboutView.vue"), about_view)?;
        }
        _ => {}
    }

    if template == "pinia" || template == "full" {
        // Pinia store
        let store_content = templates::vue3_pinia_store(typescript);
        fs::write(
            project_dir.join(format!("src/stores/counter.{}", ext)),
            store_content,
        )?;
    }

    if typescript {
        // 类型定义
        let types_content = templates::vue3_types_definition();
        fs::write(project_dir.join("src/types/index.ts"), types_content)?;
    }

    // 工具函数
    let utils_content = templates::vue3_utils(typescript);
    fs::write(
        project_dir.join(format!("src/utils/index.{}", ext)),
        utils_content,
    )?;

    println!("{} Source files generated", "📝".green());
    Ok(())
}

async fn generate_style_files(project_dir: &Path) -> Result<()> {
    // 主样式文件
    let main_css = templates::vue3_main_css();
    fs::write(project_dir.join("src/assets/css/main.css"), main_css)?;

    // 基础样式
    let base_css = templates::vue3_base_css();
    fs::write(project_dir.join("src/assets/css/base.css"), base_css)?;

    // favicon
    let favicon_placeholder = "<!-- Favicon placeholder -->";
    fs::write(project_dir.join("public/favicon.ico"), favicon_placeholder)?;

    println!("{} Style files generated", "🎨".magenta());
    Ok(())
}
